<?php

namespace App\Http\Controllers\Video;


use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use App\Utils\Qiniu\Auth; // 引入鉴权类
use App\Utils\Qiniu\Storage\UploadManager; //上传类
use App\Utils\Qiniu\Processing\PersistentFop; //上传类
use App\Utils\Qiniu\Config;
use App\Utils\Qiniu\Storage\BucketManager; //上传类
use App\Models\Video;


class QiniuController extends Controller
{
    private $accessKey = "DsyRpYhL_RZXbdyhMVMLCVAEBQ6jlwa-4CtoANmb"; 
    private $secretKey = "oronWtMQ7WlaXskpFg3fW7BK5NuP59BpBPmGWhKz";
    private $bucket = "saipubbs";
    private $extUrl = "http://v.saipubbs.com/";
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function add()
    {

        return view("qiniu.add");
    }
    public function getUpToken(){
        $bucket = $this->bucket;
        $accessKey = $this->accessKey;
        $secretKey = $this->secretKey;
        $auth = new Auth($accessKey, $secretKey);
        $upToken = $auth->uploadToken($bucket);
        //dd( $upToken);
        $ret['uptoken'] = $upToken;
        $ret['domain'] = $this->extUrl;

        return $ret;
    }

    public function store(Request $request){
	   $data = $request->input();

	   $video = new Video();
	   $video->title = $data['title'];
	   $video->url = $data['url'];
	   $video->state = $data['state'];
	   $re = $video->save();
       if($re){
           return redirect("video/index");
       }
        
    }
    //上传文件
    public function store1(Request $request){
        $file = $request->file('video');
        $realPath = $file->getRealPath();
        $name = $request->input("title");
        $ext = $file->getClientOriginalExtension();
               // dd($ext);
        $bucket = $this->bucket;
        $accessKey = $this->accessKey;
        $secretKey = $this->secretKey;
        $auth = new Auth($accessKey, $secretKey);
        $upToken = $auth->uploadToken($bucket);
        
        $filePath = $realPath;// 要上传文件的本地路径
        
        $key = $name.".".$ext;// 上传到七牛后保存的文件名
       
        $uploadMgr = new UploadManager();  // 初始化 UploadManager 对象并进行文件的上传。list($ret, $err)
        $arr = $uploadMgr->putFile($upToken, $key, $filePath);


        if ($err !== null) {
            var_dump($err);
        } else {
            var_dump($ret);
        }
    }
    //转码列表

   public function result_video($vid){

       $video_data = Video::where("id",$vid)->first();
       $video_url = $video_data->url;
       $str = explode("/",$video_url);
       $a = array_splice($str, 0, 3);
       $video_name = implode("/",$str);

       $bucket = $this->bucket;
       $accessKey = $this->accessKey;
       $secretKey = $this->secretKey;
       $auth = new Auth($accessKey, $secretKey);
       //要转码的文件所在的空间和文件名。
       $key = $video_name;

       //转码是使用的队列名称。 https://portal.qiniu.com/mps/pipeline
       $pipeline = 'ceshi';
       $force = false;
       //转码完成后通知到你的业务服务器。
       //$notifyUrl = 'http://375dec79.ngrok.com/notify.php';
        //$notifyUrl = 'http://admin.saipubbs.com/qiniu/del_qivideo';
       $policy = array(
           'callbackUrl' => 'http://admin.saipubbs.com/qiniu/del_qivideo/'.$vid,
           'callbackBody' => 'filename=$(fname)&filesize=$(fsize)'
       );
       $config = new Config();

       $pfop = new PersistentFop($auth, $config);
       $new_video_name = date("Y-m-d")."/".$video_name;
       //要进行转码的转码操作。 http://developer.qiniu.com/docs/v6/api/reference/fop/av/avthumb.html
       $fops = "avthumb/mp4/s/640x360/vb/1.4m|saveas/" . $this->base64_urlSafeEncode($bucket . ":".$new_video_name);

       list($id, $err) = $pfop->execute($bucket, $key, $fops, $pipeline, $policy, $force);
       echo "\n ====> pfop avthumb result: \n";
       if ($err != null) {
           logger()->info('1111');
           var_dump($err);
       } else {
           //echo "PersistentFop Id: $id\n";
           $video_data->url = $this->extUrl.$new_video_name;
           $video_data->old_url = $this->extUrl.$video_url;
           $video_data->is_trans = 1;
           $re = $video_data->save();
           echo "转码中。。。";

       }
        echo "<hr/>";
        //查询转码的进度和状态
       list($ret, $err) = $pfop->status($id);
       echo "\n====> pfop avthumb status: \n";
       if ($err != null) {
           var_dump($err);
       } else {
           var_dump($ret);
          // $this->del_old_video($id);
           return redirect("video/index");
       }


   }
    function base64_urlSafeEncode($data)
    {
        $find = array('+', '/');
        $replace = array('-', '_');
        return str_replace($find, $replace, base64_encode($data));
    }

    /**
     * @param $id 回传视频ID
     *        $key 视频连接
     * 转码成功后 删除原视频
     */
    function del_old_video($id){
        logger()->info('1111');
        $bucket = $this->bucket;
        $accessKey = $this->accessKey;
        $secretKey = $this->secretKey;
        $auth = new Auth($accessKey, $secretKey);
        $config = new Config();
        $bucketManager = new BucketManager($auth, $config);

        $video_data = Video::where("id",$id)->first();
        $video_url = $video_data->old_url;
        $str = explode("/",$video_url);
        $a = array_splice($str, 0, 3);
        $key = implode("/",$str);//视频原名称
        //$key = '2019-01-08/2019-01-08/2019-01-08/2019-01-08/2222/movie.mp4';
       // $key = "测试.mp4";
        $err = $bucketManager->delete($bucket, $key); //删除原视频
        if ($err) {
            print_r($err);
        }else{
            echo "删除成功";
        }







    }
}
